// pages/setInfo/setInfo.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
const app = getApp();
const db = wx.cloud.database();
var openid = app.globalData.openid;
var avatar = "";
var nickname = "";
var signature = "";
var first = false;
var info = {"avatar":"","nickname":"","signature": ""};

Page({
  
    data: {
        avatarUrl: defaultAvatarUrl,
        loginSuccessful: false,
        date:'2021-01-01',
        index:0,
        nickname:"请输入昵称",
        introduce:'介绍自己',
        phone:'手机号码',
        show: false, 
    actions: [
      {name: '男'},
      {name: '女'},
      {name: '不显示'},
    ],
    show_work: false,
    selectworks:[
      {name:'学生'},
      {name:'老师'},
      {name:'自媒体'},
      {name:'不显示'}
    ],
    currentDate: new Date().getTime(),
    minDate: new Date('1920-01-01 12:00:00').getTime(),
    dateshow:"none",
    selectDate:""
    },

    gender(e){
      this.setData({
        show:true,
      })
    },
    onSelect_G(event) {
      this.setData({
        gender:event.detail.name,
        show:false
      })
    },
    work(e){
      this.setData({
        show_work:true,
      })
    },
    onSelect_work(event) {
      this.setData({
        work:event.detail.name,
        show_work:false
      })
    },
    onInput(e) {
      var d = new Date(e.detail);
      let year = d.getYear()+1900;
      let month = d.getMonth()+1;

      this.setData({
        currentDate: e.detail,
        selectDate: year+'年'+ month+'月'
      });
    },

    date(e){
      this.setData({
        dateshow:""
      })
    },

    select(e){
      this.setData({
        dateshow:"none"
      })
      
    },
    dateValue(e){
      getColumnValue(index)
    },
    
  
    onFinish(e) {
      const { selectedOptions, value } = e.detail;
      const fieldValue = selectedOptions
          .map((option) => option.text || option.name)
          .join('/');
      this.setData({
        fieldValue,
        cascaderValue: value,
      })
    },

    onChooseAvatar(e) {
        const { avatarUrl } = e.detail;
        info["avatar"] = e.detail["avatarUrl"];
        avatar = e.detail["avatarUrl"];
        this.setData({
            avatarUrl,
        })
    },
    getText(e){
        nickname = e.detail.value;
        info["nickname"] = nickname;
    },
    getSignatureText(e){
        signature = e.detail.value;
        info["signature"] = signature;
    },
    saveError(){
        let that = this;
        let animation = wx.createAnimation({
            duration: 50,
            timingFunction: 'ease',
        });
        animation.translateX(-25).step()
        this.setData({
            errorAni:  animation.export()
        })
        setTimeout(function(){
            animation = wx.createAnimation({
                duration: 50,
                timingFunction: 'ease',
            });
            animation.translateX(+25).step()
            that.setData({
                errorAni:  animation.export()
            });
            setTimeout(function(){
                animation = wx.createAnimation({
                    duration: 50,
                    timingFunction: 'ease',
                });
                animation.translateX(0).step()
                that.setData({
                    errorAni:  animation.export()
                });
            },50);
        },50);
        //按钮抖动
    },
    saveInfo(){
        let that = this;
        let cloudPath = "avatar/" + openid + '.jpg';
        console.log({
            filePath: avatar,
            cloudPath: cloudPath});
        if ( nickname != undefined && avatar != undefined ) {
            wx.showLoading({
                title: '保存中...',
            });

            wx.cloud.uploadFile({
                filePath: avatar,
                cloudPath: cloudPath,
                success: (res) => {
                    let cloudAvatar = res.fileID;
                    db.collection("userDB").where({
                        _openid: app.globalData.openid
                    }).update({
                        data: {
                            avatar: cloudAvatar,
                            nickname: that.data.nickname,
                            signature: that.data.signature,
                            gender: that.data.gender,
                            work: that.data.work,
                            birthday: that.data.currentDate

                        },
                        success: function(res) {
                            wx.hideLoading();
                            wx.navigateBack({ delta: 0 });
                        }
                    });
                },
                complete: (res) => {
                    console.log(res);
                }
            });
        }
        else {
            wx.showToast({
              title: '没有设置头像或昵称！',
              icon: 'none'
            })
            this.saveError();
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this;
        openid = app.globalData.openid;
        if ( !openid ) {
            wx.cloud.callFunction({ //  调用云函数获取openid
                name: 'getopenid',
                complete: res => {
                    openid = res.result.openid;
                    app.globalData.openid = openid; 
                }
            });
        }
        else {
            const eventChannel = this.getOpenerEventChannel()
            eventChannel.on('acceptDataFromOpenerPage', function(data) {
                avatar = data.avatar;
                nickname = data.nickname;
                signature = data.signature;
                openid = app.globalData.openid;
                first =  data.first;
                that.setData({
                    avatarUrl: avatar,
                    nickName: nickname,
                    signature: signature
                });
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})